<template>
  <div class="messages-page">
    <div class="page-header">
      <h2>消息通知</h2>
      <p>查看您的所有通知和消息</p>
    </div>

    <div class="messages-container">
      <!-- 消息筛选 -->
      <div class="filter-section">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="全部消息" name="all">
            <div class="messages-list">
              <div v-for="message in filteredMessages" :key="message.id" class="message-item">
                <div class="message-icon">
                  <el-icon :color="getMessageIconColor(message.type)">
                    <component :is="getMessageIcon(message.type)" />
                  </el-icon>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <h4>{{ message.title }}</h4>
                    <span class="message-time">{{ message.time }}</span>
                  </div>
                  <p class="message-text">{{ message.content }}</p>
                  <div class="message-actions" v-if="message.actions">
                    <el-button 
                      v-for="action in message.actions" 
                      :key="action.key"
                      :type="action.type"
                      size="small"
                      @click="handleMessageAction(message, action)"
                    >
                      {{ action.text }}
                    </el-button>
                  </div>
                </div>
                <div class="message-status">
                  <el-badge :value="message.unread ? 1 : 0" :hidden="!message.unread">
                    <el-icon><Circle /></el-icon>
                  </el-badge>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="系统通知" name="system">
            <div class="messages-list">
              <div v-for="message in systemMessages" :key="message.id" class="message-item">
                <div class="message-icon">
                  <el-icon color="#409EFF">
                    <InfoFilled />
                  </el-icon>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <h4>{{ message.title }}</h4>
                    <span class="message-time">{{ message.time }}</span>
                  </div>
                  <p class="message-text">{{ message.content }}</p>
                </div>
                <div class="message-status">
                  <el-badge :value="message.unread ? 1 : 0" :hidden="!message.unread">
                    <el-icon><Circle /></el-icon>
                  </el-badge>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="学习提醒" name="study">
            <div class="messages-list">
              <div v-for="message in studyMessages" :key="message.id" class="message-item">
                <div class="message-icon">
                  <el-icon color="#E6A23C">
                    <Clock />
                  </el-icon>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <h4>{{ message.title }}</h4>
                    <span class="message-time">{{ message.time }}</span>
                  </div>
                  <p class="message-text">{{ message.content }}</p>
                  <div class="message-actions">
                    <el-button type="primary" size="small" @click="startLearning(message)">
                      开始学习
                    </el-button>
                    <el-button size="small" @click="snoozeReminder(message)">
                      稍后提醒
                    </el-button>
                  </div>
                </div>
                <div class="message-status">
                  <el-badge :value="message.unread ? 1 : 0" :hidden="!message.unread">
                    <el-icon><Circle /></el-icon>
                  </el-badge>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="考试通知" name="exam">
            <div class="messages-list">
              <div v-for="message in examMessages" :key="message.id" class="message-item">
                <div class="message-icon">
                  <el-icon color="#67C23A">
                    <Document />
                  </el-icon>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <h4>{{ message.title }}</h4>
                    <span class="message-time">{{ message.time }}</span>
                  </div>
                  <p class="message-text">{{ message.content }}</p>
                  <div class="message-actions">
                    <el-button type="success" size="small" @click="viewExamDetail(message)">
                      查看详情
                    </el-button>
                    <el-button type="primary" size="small" @click="bookExam(message)">
                      立即报名
                    </el-button>
                  </div>
                </div>
                <div class="message-status">
                  <el-badge :value="message.unread ? 1 : 0" :hidden="!message.unread">
                    <el-icon><Circle /></el-icon>
                  </el-badge>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 消息设置 -->
      <div class="settings-section">
        <div class="settings-header">
          <h3>消息设置</h3>
        </div>
        <div class="settings-content">
          <div class="setting-item">
            <div class="setting-label">
              <span>邮件通知</span>
              <span class="setting-desc">接收重要通知到邮箱</span>
            </div>
            <el-switch v-model="settings.emailNotification" />
          </div>
          <div class="setting-item">
            <div class="setting-label">
              <span>学习提醒</span>
              <span class="setting-desc">每日学习提醒</span>
            </div>
            <el-switch v-model="settings.studyReminder" />
          </div>
          <div class="setting-item">
            <div class="setting-label">
              <span>考试通知</span>
              <span class="setting-desc">考试相关通知</span>
            </div>
            <el-switch v-model="settings.examNotification" />
          </div>
          <div class="setting-item">
            <div class="setting-label">
              <span>系统通知</span>
              <span class="setting-desc">系统维护和更新通知</span>
            </div>
            <el-switch v-model="settings.systemNotification" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  InfoFilled, 
  Clock, 
  Document, 
  Circle, 
  Success, 
  Warning 
} from '@element-plus/icons-vue'

const router = useRouter()

// 当前激活的标签页
const activeTab = ref('all')

// 消息设置
const settings = ref({
  emailNotification: true,
  studyReminder: true,
  examNotification: true,
  systemNotification: true
})

// 所有消息数据
const allMessages = ref([])

// 加载状态
const loading = ref(false)

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const response = await getMessagesList()
    if (response.code === 200) {
      allMessages.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取消息列表失败')
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取消息设置
const fetchMessageSettings = async () => {
  try {
    const response = await getMessageSettings()
    if (response.code === 200) {
      Object.assign(settings.value, response.data || {})
    } else {
      console.error('获取消息设置失败:', response.msg)
    }
  } catch (error) {
    console.error('获取消息设置失败:', error)
  }
}

// 保存消息设置
const saveMessageSettings = async () => {
  try {
    const response = await updateMessageSettings(settings.value)
    if (response.code === 200) {
      ElMessage.success('消息设置保存成功')
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存消息设置失败:', error)
    ElMessage.error('保存失败')
  }
}

// 标记消息为已读
const markMessageAsRead = async (messageId) => {
  try {
    const response = await markMessageRead(messageId)
    if (response.code === 200) {
      // 更新本地消息状态
      const message = allMessages.value.find(m => m.id === messageId)
      if (message) {
        message.unread = false
      }
    } else {
      console.error('标记消息已读失败:', response.msg)
    }
  } catch (error) {
    console.error('标记消息已读失败:', error)
  }
}

// 批量标记消息为已读
const markAllMessagesAsRead = async () => {
  try {
    const unreadMessageIds = allMessages.value
      .filter(m => m.unread)
      .map(m => m.id)
    
    if (unreadMessageIds.length === 0) {
      ElMessage.info('没有未读消息')
      return
    }
    
    const response = await batchMarkMessagesRead(unreadMessageIds)
    if (response.code === 200) {
      // 更新本地所有未读消息状态
      allMessages.value.forEach(m => {
        if (m.unread) {
          m.unread = false
        }
      })
      ElMessage.success('已标记所有消息为已读')
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('批量标记消息已读失败:', error)
    ElMessage.error('操作失败')
  }
}

// 按类型筛选消息
const systemMessages = computed(() => allMessages.value.filter(msg => msg.category === 'system'))
const studyMessages = computed(() => allMessages.value.filter(msg => msg.category === 'study'))
const examMessages = computed(() => allMessages.value.filter(msg => msg.category === 'exam'))
const filteredMessages = computed(() => allMessages.value)

// 处理标签页点击
const handleTabClick = (tab) => {
  console.log('切换到标签页:', tab.props.name)
}

// 获取消息图标
const getMessageIcon = (type) => {
  switch (type) {
    case 'success': return Success
    case 'warning': return Warning
    case 'info': return InfoFilled
    default: return InfoFilled
  }
}

// 获取消息图标颜色
const getMessageIconColor = (type) => {
  switch (type) {
    case 'success': return '#67C23A'
    case 'warning': return '#E6A23C'
    case 'info': return '#409EFF'
    default: return '#909399'
  }
}

// 处理消息操作
const handleMessageAction = async (message, action) => {
  // 先标记消息为已读
  await markMessageAsRead(message.id)
  
  switch (action.key) {
    case 'view':
      if (message.title.includes('考试通过')) {
        router.push('/exam-results')
      } else if (message.title.includes('新课程')) {
        router.push('/videos')
      }
      break
    case 'download':
      ElMessage.success('证书下载功能开发中')
      break
    case 'book':
      router.push('/exam-booking')
      break
  }
}

// 开始学习
const startLearning = async (message) => {
  await markMessageAsRead(message.id)
  router.push('/videos')
}

// 稍后提醒
const snoozeReminder = async (message) => {
  try {
    const response = await snoozeMessage(message.id)
    if (response.code === 200) {
      ElMessage.success('已设置稍后提醒')
      await markMessageAsRead(message.id)
    } else {
      ElMessage.error(response.msg || '设置失败')
    }
  } catch (error) {
    console.error('设置稍后提醒失败:', error)
    ElMessage.error('设置失败')
  }
}

// 查看考试详情
const viewExamDetail = async (message) => {
  await markMessageAsRead(message.id)
  router.push('/exam-detail')
}

// 报名考试
const bookExam = async (message) => {
  await markMessageAsRead(message.id)
  router.push('/exam-booking')
}

// 监听设置变化，自动保存
const watchSettings = () => {
  // 使用防抖来避免频繁保存
  let saveTimer = null
  Object.keys(settings.value).forEach(key => {
    watch(() => settings.value[key], () => {
      if (saveTimer) {
        clearTimeout(saveTimer)
      }
      saveTimer = setTimeout(() => {
        saveMessageSettings()
      }, 1000)
    })
  })
}

onMounted(async () => {
  try {
    // 并行加载数据
    await Promise.all([
      fetchMessages(),
      fetchMessageSettings()
    ])
    
    // 设置监听器
    watchSettings()
  } catch (error) {
    console.error('初始化消息页面失败:', error)
  }
})
</script>

<style scoped>
.messages-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.page-header p {
  color: #666;
  margin: 0;
  font-size: 1.1rem;
}

.messages-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
}

.filter-section {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.messages-list {
  margin-top: 20px;
}

.message-item {
  display: flex;
  gap: 15px;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.message-item:hover {
  background-color: #f8f9fa;
}

.message-item:last-child {
  border-bottom: none;
}

.message-icon {
  font-size: 1.5rem;
  margin-top: 2px;
  flex-shrink: 0;
}

.message-content {
  flex: 1;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.message-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 1rem;
}

.message-time {
  font-size: 0.8rem;
  color: #999;
  flex-shrink: 0;
}

.message-text {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
}

.message-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.message-status {
  display: flex;
  align-items: flex-start;
  padding-top: 2px;
}

.settings-section {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.settings-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.settings-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.setting-label {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.setting-label span:first-child {
  color: #2c3e50;
  font-weight: 500;
}

.setting-desc {
  color: #666;
  font-size: 0.8rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .messages-container {
    grid-template-columns: 1fr;
  }
  
  .message-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .message-actions {
    flex-direction: column;
  }
  
  .message-actions .el-button {
    width: 100%;
  }
}
</style> 